package com.nsgf.library.ui.page;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.lifecycle.Observer;

import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendForm;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.LimitLine.LimitLabelPosition;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WaterInfoListBean;
import com.nsgf.library.data.bean.WaterRecordsBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityWaterChartBinding;
import com.nsgf.library.databinding.ActivityWaterDetailChartBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.adapter.FlowListAdapter;
import com.nsgf.library.ui.adapter.ReservoirListAdapter;
import com.nsgf.library.ui.adapter.WaterInfoAdapter;
import com.nsgf.library.widget.MyMarkerView;
import com.nsgf.library.widget.prckerview.TimePickerView;
import com.nsgf.skjz.utils.Kits;
import com.nsgf.skjz.utils.ToastUtils;
import com.nsgf.skjz.utils.UnitTo;
import com.nsgf.skjz.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 水情监测
 */
public class WaterActivity extends BaseActivity {

    StateHolder mState;
    private AccountRequester mAccountRequester;
    private ActivityWaterChartBinding mBinding;

    private ReservoirListAdapter mReservoirAdapter;
    private FlowListAdapter mFlowAdapter;
    private WaterInfoAdapter mWaterInfoAdapter;

    private float axisMaximum = 1f;

    LibraryInfo item;

    @Override
    protected void initViewModel() {

        mState = getActivityScopeViewModel(StateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mReservoirAdapter = new ReservoirListAdapter(this);
        mFlowAdapter = new FlowListAdapter(this);
        mWaterInfoAdapter = new WaterInfoAdapter(this);

        return new DataBindingConfig(R.layout.activity_water_chart, BR.vm, mState)
                .addBindingParam(BR.adapterWaterInfo, mWaterInfoAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);

        mState.titleBar.set("水情监测");
        mBinding = (ActivityWaterChartBinding) getBinding();
        getController().displayLoading();
        mAccountRequester.listRegimen(UserInfo.getInstance().getProjectCode());
        
        // 设置RecyclerView适配器
        mBinding.recyclerViewWater.setAdapter(mWaterInfoAdapter);
        
        // 设置点击事件
        mWaterInfoAdapter.setOnItemClickListener(new BaseDataBindingAdapter.OnItemClickListener<WaterInfoListBean>() {
            @Override
            public void onItemClick(int viewId, WaterInfoListBean item, int position) {
                // 只处理设施节点的点击
                if (item.isFacilityNode() && item.getFacilityCode() != null) {
                    // 从列表中向上查找父项目节点，获取 projectCode 和 facilityType
                    String projectCode = item.getProjectCode();
                    String facilityType = item.getFacilityType();
                    
                    // 如果设施项没有 projectCode，从列表中向上查找
                    if (projectCode == null || facilityType == null) {
                        for (int i = position - 1; i >= 0; i--) {
                            WaterInfoListBean prevItem = mWaterInfoAdapter.getItemAt(i);
                            if (prevItem != null && prevItem.isProjectNode()) {
                                if (projectCode == null) {
                                    projectCode = prevItem.getProjectCode();
                                }
                                // facilityType 可能需要从其他地方获取
                                break;
                            }
                        }
                    }
                    
                    // 如果还是没有 facilityType，使用默认值（根据API响应，通常是 "water.obj.type.8"）
                    if (facilityType == null) {
                        facilityType = "water.obj.type.8";
                    }
                    
                    String waterLevel = item.getRz() != null ? String.valueOf(item.getRz()) : "";
                    Intent intent = new Intent()
                            .putExtra("facilityCode", item.getFacilityCode())
                            .putExtra("projectCode", projectCode)
                            .putExtra("facilityType", facilityType)
                            .putExtra("waterLevel", waterLevel)
                            .putExtra("label", "汛限水位")
                            .putExtra("title", "水情监测")
                            .setClass(WaterActivity.this, WaterDetailActivity.class);
                    startActivity(intent);
                }
            }
        });
        
        mAccountRequester.getWaterInfoResult().observe(this, new Observer<ResponseStatus<List<WaterInfoListBean>>>() {
            @Override
            public void onChanged(ResponseStatus<List<WaterInfoListBean>> responseStatus) {
                getController().dismissLoading();
                if (responseStatus.getResponseCode() == 200) {
                    List<WaterInfoListBean> data = responseStatus.getData();
                    if (data != null && !data.isEmpty()) {
                        // 使用新适配器的方法扁平化数据
                        mWaterInfoAdapter.submitProjectList(data);
                    }
                } else {
                    ToastUtils.showLongToast(responseStatus.getMsg());
                }
            }
        });

        mBinding.recyclerViewWater.setNestedScrollingEnabled(false);
    }
}
